#!/usr/bin/env node
/**
 * 开发环境启动脚本
 * 同时启动 API、Admin 和管理后台前端服务
 */

const { spawn } = require('child_process')
const path = require('path')

const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  green: '\x1b[32m',
  blue: '\x1b[34m',
  yellow: '\x1b[33m',
  red: '\x1b[31m'
}

function log(color, prefix, message) {
  console.log(`${color}${prefix}${colors.reset} ${message}`)
}

// 启动服务
function startService(name, command, cwd, color) {
  log(color, `[${name}]`, `启动中...`)
  
  // 使用 pnpm 替换 npm
  const pnpmCommand = command.replace(/npm /g, 'pnpm ')
  const [cmd, ...args] = pnpmCommand.split(' ')
  const process = spawn(cmd, args, {
    cwd: path.join(__dirname, cwd),
    shell: true,
    stdio: 'inherit'
  })
  
  process.on('error', (error) => {
    log(colors.red, `[${name}]`, `错误: ${error.message}`)
  })
  
  process.on('exit', (code) => {
    if (code !== 0 && code !== null) {
      log(colors.red, `[${name}]`, `退出码: ${code}`)
    }
  })
  
  return process
}

console.log(`${colors.bright}${colors.green}`)
console.log('╔═══════════════════════════════════════╗')
console.log('║   图片小程序后端服务启动中...        ║')
console.log('╚═══════════════════════════════════════╝')
console.log(colors.reset)

// 启动三个服务
const api = startService('API', 'pnpm run dev', 'api', colors.blue)
const admin = startService('Admin', 'pnpm run dev', 'admin', colors.yellow)
const frontend = startService('Frontend', 'pnpm run dev', 'admin-frontend', colors.green)

// 等待一下后显示访问地址
setTimeout(() => {
  console.log('\n' + colors.bright + colors.green)
  console.log('╔═══════════════════════════════════════╗')
  console.log('║   服务已启动，访问地址：              ║')
  console.log('╠═══════════════════════════════════════╣')
  console.log('║   API 服务:    http://localhost:3000  ║')
  console.log('║   Admin 服务:  http://localhost:3001  ║')
  console.log('║   管理后台:    http://localhost:3002  ║')
  console.log('╚═══════════════════════════════════════╝')
  console.log(colors.reset + '\n')
}, 2000)

// 优雅退出
process.on('SIGINT', () => {
  console.log('\n' + colors.yellow + '正在关闭服务...' + colors.reset)
  api.kill()
  admin.kill()
  frontend.kill()
  process.exit(0)
})

process.on('SIGTERM', () => {
  api.kill()
  admin.kill()
  frontend.kill()
  process.exit(0)
})

